package com.apchernykh.rozhlasapp.ui.stations;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.app.Activity;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import com.apchernykh.ceskyrozhlas.basic.R;
import com.apchernykh.rozhlasapp.ui.RozhlasAppBaseFragmentActivity;
import com.apchernykh.types.ApplicationModel;
import com.apchernykh.types.StationInfo;

public class StationListAdapter extends ArrayAdapter<StationInfo> {

	int mLayoutId;

	public StationListAdapter(Context iContext, int iTextViewResourceId,
			List<StationInfo> iObjects) {
		super(iContext, iTextViewResourceId, iObjects);
		mLayoutId = iTextViewResourceId;
	}

	@Override
	public View getView(int iPosition, View iConvertView, ViewGroup iParent) {
		//Sync view positions with station ids, as soon as the list is shown.
		getItem(iPosition).mStationId = iPosition;
		View aRow = iConvertView;
		if (aRow == null) {
			LayoutInflater aInflater = ((Activity) getContext())
					.getLayoutInflater();
			aRow = aInflater.inflate(mLayoutId, iParent, false);
		}

		StationInfoView aView = (StationInfoView) aRow
				.findViewById(R.id.sivStationInfo);
		aView.set_stationInfo(getItem(iPosition));
		refreshStationPlayingNowInfo(aView, getItem(iPosition));
		return aRow;
	}

	void refreshStationPlayingNowInfo(final StationInfoView iView,
			final StationInfo iStationInfo) {
		if (iStationInfo == null) {
			return;
		}
		final long aCurrentTime = System.currentTimeMillis();
		if ( aCurrentTime > iStationInfo.mExpirationTime) {
//			ConditionalLog.e(iStationInfo.mShortName + " refreshing "+String.valueOf(aCurrentTime)+" > "+String.valueOf(iStationInfo.mExpirationTime));
			iStationInfo.mExpirationTime = aCurrentTime + 15000;
			//Just before we refresh station info, we should set it's expiration time to the future
			AsyncTask<Integer, Integer, Boolean> aAsyncStationsInfoRefreshTask = new AsyncTask<Integer, Integer, Boolean>() {
				@Override
				protected Boolean doInBackground(Integer... iParams) {
					try {
						iStationInfo.forceRefresh();
						if (iStationInfo.mStationId == RozhlasAppBaseFragmentActivity.mApplicationModel.mStationSelected) {
								RozhlasAppBaseFragmentActivity.mApplicationModel.mOnViewsExpiredListener
										.onViewExpired();
						}

						return true;
					} catch (Exception e) {
						e.printStackTrace();
					}
					return false;
				}

				@Override
				protected void onPostExecute(Boolean iUpdateSuccessful) {
					if (iUpdateSuccessful && iStationInfo == iView.mStationInfo) {
						iView.set_stationInfo(iStationInfo);
//						ConditionalLog.e(iStationInfo.mShortName + " refreshed "+String.valueOf(iStationInfo.mExpirationTime));
					} else {
//						Log.d(ApplicationModel.TAG,
//								iStationInfo.mShortName + " scrolled out");
					}
				}
			};
			if(RozhlasAppBaseFragmentActivity.mApplicationModel.mInetInfo.isDownloadAllowed())
			{
				aAsyncStationsInfoRefreshTask.execute(0);
			}		} else {
			ApplicationModel
					.notifyViewExpirationTime(iStationInfo.mExpirationTime);
		}
	}

	public List<StationInfo> setData(List<StationInfo> iData) {

		if (mergeStationInfos(iData)) {
			// sometimes, complete clear/repopulate is not needed,
			// so we return if merge of the input data with existing one was
			// successful

			// TODO: instead of merging here, maybe overwrite underlying
			// collection, passed in the constructor?
			ArrayList<StationInfo> aStationsList = new ArrayList<StationInfo>(
					getCount());
			for (int aStationNumber = 0; aStationNumber < getCount(); aStationNumber++) {
				aStationsList.add(getItem(aStationNumber));
			}
			return aStationsList;
		}

		clear();
		if (iData != null) {
			for (StationInfo aStation : iData) {
				add(aStation);
			}
		}
		notifyDataSetChanged();
		return iData;
	}

	private boolean mergeStationInfos(List<StationInfo> iStationsList) {
		int aPosition = 0;
		if (iStationsList == null || iStationsList.size() != getCount()) {
			return false;
		}
		for (StationInfo aStation : iStationsList) {
			if (aStation.mShortName.compareTo(getItem(aPosition).mShortName) != 0) {
				// TODO: find out why we have nulls here.
				return false;
			}
			getItem(aPosition).copy(aStation);
			aPosition++;
		}
		return true;
	}

}
